//表一
var columns1 = [
    [{checkbox: true},
        {field: 'id', title: '标示符', align: 'center', valign: 'middle', colspan: 1, rowspan: 1},
        {
            field: 'showId', title: '序号', align: 'center', valign: 'middle', colspan: 1, rowspan: 1,
            formatter: function (value, row, index) {
                return index + 1;
            }
        },
        {field: 'companyType', title: "企业类型", align: 'center', valign: 'middle', colspan: 1, rowspan: 1,},
        {field: 'productName', title: "产品名称", align: 'center', valign: 'middle', colspan: 1, rowspan: 1,},
        {field: 'unitBasic', title: "单位产品基准排水量", align: 'center', valign: 'middle', colspan: 1, rowspan: 1},
        {field: 'productAmount', title: "产品产量", align: 'center', valign: 'middle', colspan: 1, rowspan: 1,},
    ],
]

//表二
var columns2 = [
    [{checkbox: true},
        {field: 'id', title: '标示符', align: 'center', valign: 'middle', colspan: 1, rowspan: 1},
        {
            title: '序号', field: 'showId', align: 'center', valign: 'middle',
            formatter: function (value, row, index) {
                return index + 1;
            }
        },
        {field: 'totalAmount', title: "排水总量", align: 'center', valign: 'middle', colspan: 1, rowspan: 1,},
        {field: 'position', title: "监控位置", align: 'center', valign: 'middle', colspan: 1, rowspan: 1,},
        {field: 'note', title: "备注", align: 'center', valign: 'middle', colspan: 1, rowspan: 1},
    ],
]

var metaList;
var table1List;
var table2List;
var computeResult;
var lastId;
var stdNumber;

var Table1Init = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        var tableName = document.getElementById("table1").createCaption();
        tableName.innerHTML = "<b>表1</b>";
        $('#table1').bootstrapTable({
            url: '/waste_water/table1_select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: false,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 100,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: columns1,
            onLoadSuccess: function (data) {
                var data = $('#table1').bootstrapTable('getData', false);//获取全部数据
            },
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            lastId: label_id,
        };
        return temp;
    };
    return oTableInit;
};

var Table2Init = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        var tableName = document.getElementById("table2").createCaption();
        tableName.innerHTML = "<b>表2</b>";
        $('#table2').bootstrapTable({
            url: '/waste_water/table2_select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar2',                //工具按钮用哪个容器
            striped: false,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 100,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: columns2,
            onLoadSuccess: function (data) {
                var data = $('#table2').bootstrapTable('getData', false);//获取全部数据
            },
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            lastId: label_id,
        };
        return temp;
    };
    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {
        //初始化页面上面的按钮事件
        //新增按钮
        $("#btn_add").click(function () {
            $('#new_company_type').val('');
            $("#new_productName").val('');//初始化
            $("#new_unitBasic").val('');
            $("#new_productAmount").val('');
            $('#new_data').modal();
        });

        //新增框内的提交
        $('#new_data_submit').on('click', function () {
            var companyType = $('#new_company_type').val()
            var productName = $('#new_productName').val()
            var unitBasic = $('#new_unitBasic').val()
            var productAmount = $('#new_productAmount').val()

            unitBasic = parseFloat(unitBasic);
            productAmount = parseFloat(productAmount);

            $.ajax({
                type: "post",
                url: "/waste_water/table1Insert",
                async: false,
                data: {
                    'companyType': companyType,
                    'productName': productName,
                    'unitBasic': unitBasic,
                    'productAmount': productAmount,
                    'lastId': label_id
                },
                success: function (data) {
                    bootoast({
                        message: '插入成功',
                        position: 'top',
                        type: 'success',
                        timeout: 2,
                    });
                    $("#table1").bootstrapTable('refresh');
                    $('#new_data').modal('hide');
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });

        // 删除按钮
        $("#btn_delete").click(function () {
            var arrselections = $("#table1").bootstrapTable('getSelections');
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            values = [];
            for (var i = 0; i < arrselections.length; i++)
                values.push(arrselections[i].id);
            bootbox.confirm({
                message: "确认要删除选择的数据吗？",
                locale: 'zh_CN',
                title: '操作提示',
                callback: function (result) {
                    if (result) {
                        $.ajax({
                            type: "post",
                            url: "/waste_water/delete",
                            data: JSON.stringify(values),
                            contentType: "application/json",
                            success: function (data) {
                                bootoast({
                                    message: '删除成功',
                                    position: 'top',
                                    type: 'success',
                                    timeout: 1.5,
                                });
                                $("#table1").bootstrapTable('refresh');
                            },
                            error: function () {
                                bootoast({
                                    message: '通讯异常',
                                    position: 'top',
                                    type: 'danger',
                                    timeout: 1.5,
                                });
                            }
                        });
                    }
                }
            })

        });

        //编辑按钮
        $("#btn_edit").click(function () {
            var arrselections = $("#table1").bootstrapTable('getSelections');

            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            } else if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            $('#edit_company_type').val(arrselections[0].companyType);
            editCompanyTypeChange();
            $('#edit_productName').val(arrselections[0]['productName']);
            $('#edit_unitBasic').val(arrselections[0]['unitBasic']);
            $('#edit_productAmount').val(arrselections[0]['productAmount']);
            $('#edit_data').modal()

        });
        // 编辑框内的提交
        $('#edit_data_submit').click(function () {
            var id = $("#table1").bootstrapTable('getSelections')[0]['id'];//更改处
            var companyType = $('#edit_company_type').val()
            var productName = $('#edit_productName').val()
            var unitBasic = $('#edit_unitBasic').val()
            var productAmount = $('#edit_productAmount').val()

            $.ajax({
                type: "get",
                url: "/waste_water/table1update",
                async: false,
                data: {
                    'id': id,
                    'companyType': companyType,
                    'productName': productName,
                    'unitBasic': unitBasic,
                    'productAmount': productAmount,
                },
                success: function (data) {
                    bootoast({
                        message: '更新成功',
                        position: 'top',
                        type: 'success',
                        timeout: 2,
                    });
                    $("#edit_data").modal('hide');
                    $("#table1").bootstrapTable('refresh');

                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });

        //编辑按钮2
        $("#btn_edit2").click(function () {
            var arrselections = $("#table2").bootstrapTable('getSelections');

            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行编辑',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }
            if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            $('#edit_totalAmount').val(arrselections[0]['totalAmount']);
            editPosition();
            $('#edit_position').val(arrselections[0]['position']);
            $('#edit_note').val(arrselections[0]['note']);
            $('#edit_data2').modal()
        });

        // 编辑框内的提交
        $('#edit_data_submit2').click(function () {
            var id = $("#table2").bootstrapTable('getSelections')[0]['id'];//更改处
            var totalAmount = $('#edit_totalAmount').val()
            var position = $('#edit_position').val()
            var note = $('#edit_note').val()
            totalAmount = parseFloat(totalAmount);

            $.ajax({
                type: "get",
                url: "/waste_water/table2update",
                async: false,
                data: {
                    'id': id,
                    'totalAmount': totalAmount,
                    'position': position,
                    'note': note,
                },
                success: function (data) {
                    bootoast({
                        message: '更新成功',
                        position: 'top',
                        type: 'success',
                        timeout: 2,
                    });
                    $("#edit_data2").modal('hide');
                    $("#table2").bootstrapTable('refresh');

                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });

        //计算按钮
        $('#calculate').click(function () {
            lastId = label_id;
            stdNumber = label_eva_basis;
            var temp = 0;
            for (var i = 0; i < table1List.length; i++) {
                temp += table1List[i].productAmount * table1List[i].unitBasic;
            }
            computeResult = temp / table2List[0].totalAmount;

            $('#page-wrapper').load('pages/waste_water_sub.html');
        });

        //返回按钮
        $('#btn_return').on('click', function () {
            //点击返回按钮，返回到label页，将状态改为填写中
            $.ajax({
                type: "post",
                url: "/waste_water/label_update",
                async: false,
                data: {
                    'id': label_id,
                    'state': "填写中"
                },
                success: function (data) {
                    $('#page-wrapper').load('pages/entity_eva_waste_water_main.html');
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });
    };

    return oInit;
};

var hasPermission = function () {
    queryPermission('废水评估', '新增', 'btn_add')
    queryPermission('废水评估', '编辑', 'btn_edit')
    queryPermission('废水评估', '删除', 'btn_delete')
}

$(function () {
    hasPermission();

    if (operation != 'edit') {
        getTable1Data()
        getTable2Data();
        lastId = label_id;
        stdNumber = label_eva_basis;
        var temp = 0;
        for (var i = 0; i < table1List.length; i++) {
            temp += table1List[i].productAmount * table1List[i].unitBasic;
        }
        computeResult = temp / table2List[0].totalAmount;
        $('#page-wrapper').load('pages/waste_water_sub.html');
    }

    //获取元数据内容
    getMetaData();
    getTable1Data();
    getTable2Data();
    if (table2List.length < 1) {
        insertTable2();
    }

    var table1 = new Table1Init();
    table1.Init();

    var table2 = new Table2Init();
    table2.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    //3.隐藏列
    $('#table1').bootstrapTable('hideColumn', 'id');
    $('#table2').bootstrapTable('hideColumn', 'id');
    $('#table2').bootstrapTable('hideColumn', 'showId');

});

function getMetaData() {
    $.ajax({
        type: "get",
        url: "/waste_water/get_meta_data",
        async: false,
        data: {stdNumber: label_eva_basis},
        success: function (data) {
            metaList = data;
//               console.log(metaList)
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
}

function getTable1Data() {
    $.ajax({
        type: "get",
        url: "/waste_water/get_table1_data",
        async: false,
        data: {lastId: label_id},
        success: function (data) {
            table1List = data;
//               console.log(table1List)
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
}

function getTable2Data() {
    $.ajax({
        type: "get",
        url: "/waste_water/get_table2_data",
        async: false,
        data: {lastId: label_id},
        success: function (data) {
            table2List = data;
//               console.log(table2List)
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
}

function newCompanyTypeChange() {
    document.getElementById('new_productName').options.length = 1;
    $('#new_unitBasic').val('');
    for (var i = 0; i < metaList.length; i++) {
        var companyType = $('#new_company_type').val();
        if (metaList[i].companyType == companyType) {
            $("#new_productName").append("<option value=" + metaList[i].productName + ">" + metaList[i].productName + "</option>");
        }
    }
}

function newProductNameCheck() {
    var companyType = $('#new_company_type').val();
    if (companyType == '' || companyType == null) {
        alert("请先选择企业类型");
    }
}

function newProductNameChange() {
    $('#new_unitBasic').val('');

    var companyType = $('#new_company_type').val();
    var productName = $('#new_productName').val();
    for (var i = 0; i < metaList.length; i++) {
        if (metaList[i].companyType == companyType && productName == metaList[i].productName) {
            $('#new_unitBasic').val(metaList[i].baseline);
        }
    }
}

function editCompanyTypeChange() {
    document.getElementById('edit_productName').options.length = 1;
    $('#edit_unitBasic').val('');
    for (var i = 0; i < metaList.length; i++) {
        var companyType = $('#edit_company_type').val();
        if (metaList[i].companyType == companyType) {
            $("#edit_productName").append("<option value=" + metaList[i].productName + ">" + metaList[i].productName + "</option>");
        }
    }
}

function editProductNameCheck() {
    var companyType = $('#edit_company_type').val();
    if (companyType == '' || companyType == null) {
        alert("请先选择企业类型");
    }
}

function editProductNameChange() {
    $('#edit_unitBasic').val('');
    var companyType = $('#edit_company_type').val();
    var productName = $('#edit_productName').val();
    for (var i = 0; i < metaList.length; i++) {
        if (metaList[i].companyType == companyType && metaList[i].productName == productName) {
            $('#edit_unitBasic').val(metaList[i].baseline);
        }
    }
}

var flag = 0;

function editPosition() {
    if (flag == 0) {
        for (var i = 0; i < metaList.length; i++) {
            for (var j = 0; j < table1List.length; j++) {
                if (metaList[i].productName == table1List[j].productName) {
                    $("#edit_position").append("<option value=" + metaList[i].position + ">" + metaList[i].position + "</option>");
                }
            }
        }
        flag = 1;
    }
}


function insertTable2() {

    var totalAmount = "0";
    var position = "待编辑";
    var note = " ";

    totalAmount = parseFloat(totalAmount);

    $.ajax({
        type: "post",
        url: "/waste_water/table2Insert",
        async: false,
        data: {
            'totalAmount': totalAmount,
            'position': position,
            'note': note,
            'lastId': label_id
        },
        success: function (data) {
            bootoast({
                message: '插入成功',
                position: 'top',
                type: 'success',
                timeout: 2,
            });
            $("#table2").bootstrapTable('refresh');
            //$('#new_data').modal('hide');
        },
        error: function () {
            bootoast({
                message: '通讯异常',
                position: 'top',
                type: 'danger',
                timeout: 1.5,
            });
        }
    });
}
